# 1 导入库及设置GPU
# 1.1 导入库
import torch
import torch.nn as nn
from torchvision import transforms, datasets
from torchvision.models import VGG16_Weights, vgg16
import copy
import matplotlib.pyplot as plt
from datetime import datetime
import warnings
warnings.filterwarnings("ignore")
plt.rcParams['font.sans-serif']    = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False      # 用来正常显示负号
plt.rcParams['figure.dpi']         = 100        #分辨率

# 1.2 设置GPU
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# 2 数据预处理
# 2.1 数据下载
data_dir = '/Users/sunhaoqing/Desktop/pythonProject/深度学习/2 Pytorch入门/data/天气识别'

# 2.2 数据标准化
train_transforms = transforms.Compose([
    transforms.Resize([224, 224]),
    transforms.ToTensor(),
    transforms.Normalize(
        mean=[0.485, 0.456, 0.406],
        std=[0.229, 0.224, 0.225]
    )
])

total_data = datasets.ImageFolder(data_dir, transform=train_transforms)

# 2.3 划分数据集
train_size = int(0.8 * len(total_data))
test_size  = len(total_data) - train_size
g = torch.Generator().manual_seed(42)
train_dataset, test_dataset = torch.utils.data.random_split(total_data, [train_size, test_size], generator=g)

# 2.4 数据加载
batch_size = 32

train_dl = torch.utils.data.DataLoader(
    train_dataset,
    batch_size=batch_size,
    shuffle=True,
    num_workers=0
)

test_dl = torch.utils.data.DataLoader(
    test_dataset,
    batch_size=batch_size,
    shuffle=False,
    num_workers=0
)

# 3 调用官方VGG-16模型
classeNames = 17

# 3.1 加载vgg16预训练模型
model = vgg16(weights=VGG16_Weights.IMAGENET1K_V1).to(device)

# 3.2 迁移学习：冻结卷积层
for param in model.features.parameters():
    param.requires_grad = False

# 3.3 迁移学习：替换最后分类层
num_classes = len(total_data.classes)
model.classifier._modules['6'] = nn.Linear(4096, num_classes)

# 4 训练准备
# 4.1 设置超参数
model = model.to(device)

loss_fn = nn.CrossEntropyLoss()

learn_rate = 1e-4
lambda1 = lambda epoch: (0.92 ** (epoch // 2))
# optimizer = torch.optim.SGD(model.parameters(), lr=learn_rate)
optimizer = torch.optim.SGD(filter(lambda p: p.requires_grad, model.parameters()), lr=learn_rate)
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda1)

# 4.2 训练函数
def train(dataloader, model, loss_fn, optimizer):
    size        = len(dataloader.dataset)   # 训练集大小
    num_batches = len(dataloader)           # 批次数目

    # 初始化训练损失和准确率
    train_loss = 0
    train_acc  = 0

    # 获取图片标签
    for X,y in dataloader:
        X = X.to(device)
        y = y.to(device)

        # 计算预测误差
        pred = model(X)
        loss = loss_fn(pred, y)

        # 反向传播
        optimizer.zero_grad()   # grad属性归零
        loss.backward()         # 反向传播
        optimizer.step()        # 每一步自动更新

        # 记录acc与loss
        train_acc += (pred.argmax(1) == y).type(torch.float).sum().item()
        train_loss += loss.item()

    train_acc /= size
    train_loss /= num_batches

    return train_acc, train_loss

# 4.3 测试函数
def test(dataloader, model, loss_fn):
    size = len(dataloader.dataset)
    num_batches = len(dataloader)
    test_loss, test_acc = 0, 0

    # 当不进行训练时，停止梯度更新，节省计算内存消耗
    with torch.no_grad():
        for imgs, target in dataloader:
            imgs, target = imgs.to(device), target.to(device)

            # 计算loss
            target_pred = model(imgs)
            loss = loss_fn(target_pred, target)

            test_loss += loss.item()
            test_acc += (target_pred.argmax(1) == target).type(torch.float).sum().item()

    test_acc /= size
    test_loss /= num_batches

    return test_acc, test_loss

# 5 训练
# 5.1 初始化设置
epochs = 40

train_loss = []
train_acc  = []
test_loss  = []
test_acc   = []

best_acc = 0

# 5.2 开始
for epoch in range(epochs):

    model.train()
    epoch_train_acc, epoch_train_loss = train(train_dl, model, loss_fn, optimizer)
    scheduler.step()

    model.eval()
    epoch_test_acc, epoch_test_loss = test(test_dl, model, loss_fn)

    # 保存最佳模型到 best_model
    if epoch_test_acc > best_acc:
        best_acc = epoch_test_acc
        best_model = copy.deepcopy(model)

    train_acc.append(epoch_train_acc)
    train_loss.append(epoch_train_loss)
    test_acc.append(epoch_test_acc)
    test_loss.append(epoch_test_loss)

    # 获取当前的学习率
    lr = optimizer.state_dict()['param_groups'][0]['lr']

    template = ('Epoch:{:2d}, Train_acc:{:.1f}%, Train_loss:{:.3f}, Test_acc:{:.1f}%, Test_loss:{:.3f}, Lr:{:.2E}')
    print(template.format(epoch + 1, epoch_train_acc * 100, epoch_train_loss,
                              epoch_test_acc * 100, epoch_test_loss, lr))

# 5.3 保存最佳模型到文件中
PATH = './best_model.pth'  # 保存的参数文件名
torch.save(best_model.state_dict(), PATH)

#6 可视化
current_time = datetime.now() # 获取当前时间

epochs_range = range(epochs)

plt.figure(figsize=(12, 3))

plt.subplot(1, 2, 1)
plt.plot(epochs_range, train_acc, label='Training Accuracy')
plt.plot(epochs_range, test_acc, label='Test Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.xlabel(current_time) # 打卡请带上时间戳，否则代码截图无效

plt.subplot(1, 2, 2)
plt.plot(epochs_range, train_loss, label='Training Loss')
plt.plot(epochs_range, test_loss, label='Test Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.xlabel(current_time) # 打卡请带上时间戳，否则代码截图无效

plt.show()